package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisVOService;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.ModelUtils;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/travel")
public class TravelController {
    @Reference
    private ITravelService travelService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private ITravelCommentService travelCommentService;

    @Reference
    private ITravelStatisVOService travelStatisVOService;

    /**
     * 游记首页
     *
     * @param model
     * @param qo
     * @return
     */
    @RequestMapping("")
    public String list(Model model, @ModelAttribute("qo") TravelQuery qo) {
        //pageInfo
        model.addAttribute("pageInfo", travelService.query(qo));
        return "travel/list";
    }

    /**
     * 游记编辑
     *
     * @param model
     * @param id
     * @return
     */
    @RequireLogin
    @RequestMapping("input")
    public String input(Model model, Long id) {
        //dests
        model.addAttribute("dests", destinationService.list());
        //tv
        if (id != null) {
            Travel tv = travelService.get(id);
            model.addAttribute("tv", tv);
        }
        return "travel/input";
    }

    /**
     * 游记内容页面
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/detail")
    public String detail(Model model, Long id) {
        //detail
        Travel travel = travelService.get(id);
        model.addAttribute("detail", travel);
        //toasts
        Long destId = travel.getDest().getId();
        ModelUtils.addToastsAndDest(destinationService, model, destId);
        //strategyDetails
        model.addAttribute("strategyDetails", strategyDetailService.queryViewNumTop3(destId));

        //travels
        model.addAttribute("travels", travelService.queryViewNumTop3(destId));

        // 阅读数 +1
        travelStatisVOService.increaseViewnum(id, 1);

        //list
        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setTravelId(id);
        qo.setPageSize(Integer.MAX_VALUE);
        List list = travelCommentService.query(qo).getContent();
        model.addAttribute("list", list);
        model.addAttribute("vo", travelStatisVOService.getTravelStatisVO(id));
        return "travel/detail";
    }

    @Value("${file.path}")
    private String filePath;

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }

    /**
     * 新增或修改游记
     *
     * @param travel
     * @param userInfo
     * @return
     */
    @RequireLogin
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo userInfo) {
        travel.setAuthor(userInfo);
        Long travelId = travelService.saveOrUpdate(travel);
        return AjaxResult.success().addData(travelId);
    }

    @RequestMapping("/commentAdd")
    public String commentAdd(Model model, TravelComment comment, int floor, @UserParam UserInfo userInfo) {
        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());
        comment.setLevel(userInfo.getLevel());
        comment.setCity(userInfo.getCity());
        comment.setHeadUrl(userInfo.getHeadImgUrl());

        comment = travelCommentService.commentAdd(comment);

        // 评论数 +1
        travelStatisVOService.increaseReplynum(comment.getTravelId(), 1);

        model.addAttribute("c", comment);
        long f = travelCommentService.getCount(comment.getTravelId());
        model.addAttribute("floor", f);
        return "travel/commentTpl";
    }

    // 收藏游记
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(@UserParam UserInfo userInfo, Long tid) {
        if (userInfo == null) {
            // 未登录
            AjaxResult result = new AjaxResult(false, "请先登录!");
            result.setCode(AjaxResult.NO_LOGIN);
            return result;
        }
        // 收藏:true;  取消收藏:false
        boolean ret = travelStatisVOService.favor(userInfo.getId(), tid);

        return new AjaxResult(ret, "").addData(travelStatisVOService.getTravelStatisVO(tid));
    }

    // 顶 游记
    @RequestMapping("/travelThumbup")
    @ResponseBody
    public Object travelThumbup(@UserParam UserInfo userInfo, Long tid) {
        if (userInfo == null) {
            AjaxResult result = new AjaxResult(false, "请先登录!");
            result.setCode(AjaxResult.NO_LOGIN);
            return result;
        }
        boolean ret = travelStatisVOService.travelThumbup(userInfo.getId(), tid);
        return new AjaxResult(ret, "").addData(travelStatisVOService.getTravelStatisVO(tid));
    }

    @RequestMapping("/share")
    @ResponseBody
    public Object share(@UserParam UserInfo userInfo, Long tid) {
        if (userInfo == null) {
            // 未登录
            AjaxResult result = new AjaxResult(false, "请先登录!");
            result.setCode(AjaxResult.NO_LOGIN);
            return result;
        }
        travelStatisVOService.travelShare(tid);
        return AjaxResult.success().addData(travelStatisVOService.getTravelStatisVO(tid));
    }
}
